/**
 ***********************************************************************************************************************
 * Copyright (c) 2021, XIE LI Co.,Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 *
 * @file        udp_client.c
 *
 * @brief       udp_client functions.
 *
 * @revision
 * Date         Author          Notes
 * 2021-09-30   Xie Li      First Version
 ***********************************************************************************************************************
 */
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>

#define HOST_IP_ADDR    "192.168.101.3"
#define HOST_PORT_NUM   50000

/**
 ***********************************************************************************************************************
 * @brief           udp_client_run
 *
 * @param[in]       none
 *
 * @return          none
 ***********************************************************************************************************************
 */
int udp_client_run(void)
{
    struct sockaddr_in srv_addr;
    int sock_fd;
    char buf[64];
    char *message = "hello server";

    sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock_fd == -1) {
        printf("Socket create failed\r\n");
        return -1;
    }

    memset(&srv_addr, 0, sizeof(srv_addr));
    srv_addr.sin_family = AF_INET;
    srv_addr.sin_addr.s_addr = inet_addr(HOST_IP_ADDR);
    srv_addr.sin_port = htons(HOST_PORT_NUM);

    /* 数据报socket上使用connect */
    if (connect(sock_fd, (struct sockaddr *)&srv_addr, sizeof(struct sockaddr_in)) == -1) {
        printf("Connect to server failed, errno=%d\r\n", errno);
        goto exit;
    }

    while (1) {
        int len = send(sock_fd, message, strlen(message), 0);
        if (len < 0) {
            printf("Send to server failed, errno=%d\r\n", errno);
            goto exit;
        }

        len = recv(sock_fd, buf, sizeof(buf), 0);
        if (len == -1) {
            printf("Receive from server failed, errno=%d\r\n", errno);
            goto exit;
        }
        printf("Received %d bytes from server (%s:%d):\r\n", len, HOST_IP_ADDR, HOST_PORT_NUM);
        printf("%.*s\r\n", len, buf);

        sleep(1);
    }

    return 0;

exit:
    shutdown(sock_fd, SHUT_RDWR);
    // close(sock_fd);
    return -1;
}
